﻿using Demo.Common;
using Demo.Web.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo.Web.api.xcx
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string opt = DTRequest.GetString("opt");
            switch (opt)
            {
                case "onLogin": onLogin(); break;                           //微信登录

            }
        }

        /// <summary>
        /// 微信登录
        /// </summary>
        public void onLogin()
        {
            BLL.xcxconfig confing_bll = new BLL.xcxconfig();
            Model.xcxconfig confing_model = confing_bll.loadConfig();
            string code = DTRequest.GetString("code");
            string url = string.Format(DTKeys.XCX_LOGIN_URL, confing_model.AppId, confing_model.AppSecret, code);
            string res = Utils.HttpGet(url);
            Dictionary<string, object> dr = JsonHelper.DataRowFromJSON(res);
            try
            {
                string openid = dr["openid"].ToString();
                string session_key = dr["session_key"].ToString();
                BLL.weixin_user bll = new BLL.weixin_user();
                //根据openid查询数据库，如果不存在则添加用户
                if (!bll.Exists("openid", openid))
                {
                    Model.weixin_user model = new Model.weixin_user();
                    model.openid = openid;
                    model.session_key = session_key;
                    model.user_name = bll.GetRandomName(6);
                    int id = bll.Add(model);
                    if (id > 0)
                    {
                        model.id = id;
                        Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "新用户添加成功！", model)));
                        Response.End();
                    }
                    else
                    {
                        Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "添加用户失败！", res)));
                        Response.End();
                    }
                }
                else
                {
                    Model.weixin_user model = bll.GetModel(openid);
                    model.session_key = session_key;
                    bll.Update(model);
                    Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "用户存在！", model)));
                    Response.End();
                }
            }
            catch (System.Collections.Generic.KeyNotFoundException)
            {
                Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", $"获取openid失败！code:{dr["errcode"]},ermsg{dr["errmsg"]}")));
                Response.End();
            }
        }

       
    }
}